package cn.com.twoke.easyproject.handler.mybatisplus;

import cn.com.twoke.easyproject.common.context.holder.UserLoginContextHolder;
import cn.com.twoke.easyproject.handler.mybatisplus.fill.*;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 元数据灯芯
 */
@Component
public class MetaObjectHandlerImpl implements MetaObjectHandler {
    /**
     * 逻辑删除默认值
     */
    @Value("${mybatis-plus.global-config.db-config.logic-not-delete-value}")
    private Integer logicNotDeleteValue;
    /**
     * 版本号乐观锁
     */
    private final Long defaultVersionValue = 1L;

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        if (metaObject.getOriginalObject() instanceof CreateUserFillable fillable) {
            fillable.setCreateUser(UserLoginContextHolder.get().getUid()); // 插入创建用户ID
        }
        if (metaObject.getOriginalObject() instanceof CreateTimeFillable fillable) {
            fillable.setCreateTime(now); // 插入创建时间
        }
        if (metaObject.getOriginalObject() instanceof UpdateUserFillable fillable) {
            fillable.setUpdateUser(UserLoginContextHolder.get().getUid()); // 插入更新用户
        }
        if (metaObject.getOriginalObject() instanceof UpdateTimeFillable fillable) {
            fillable.setUpdateTime(now); // 插入更新时间
        }
        if (metaObject.getOriginalObject() instanceof LogicFillable fillable) {
            fillable.setIsDeleted(logicNotDeleteValue); // 插入逻辑删除默认
        }
        if (metaObject.getOriginalObject() instanceof VersionFillable fillable) {
            fillable.setVersion(defaultVersionValue); // 插入版本号悲观锁
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        if (metaObject.getOriginalObject() instanceof UpdateUserFillable fillable) {
            fillable.setUpdateUser(UserLoginContextHolder.get().getUid());
        }
        if (metaObject.getOriginalObject() instanceof UpdateTimeFillable fillable) {
            fillable.setUpdateTime(now);
        }
    }

}
